package com.eims.sls_app.ui;

import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.MySingleton;
import com.android.volley.toolbox.StringRequest;
import com.contans.view.TextVo;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.BaseHelper;
import com.eims.sls_app.view.MyToast;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

import bls.juejin.cn.R;

public class AmountOfCharge extends MyBaseActivity implements OnClickListener {
    public final static String TAG = "AmountOfCharge";
    public String feeName = "好球充值";
    public String feePrice = "";
    public String feeDesc = "好球充值";
    public String Key = "4297f44b13955235245b2497399d7a93";
    // public String Key_kefu = "4297f44b13955235245b2497399d7a93";
    public ImageButton btn_back;
    public EditText recahge_et_money;
    // 立即充值
    public Button recharge_btn_ok;
    public static Context mContext;
    // 充值类型1,银联2,支付宝3,微信4.支付宝快捷支付
    public int type;
    // Request
    private Request jsonObjectRequest;
    private String RE = "tb_Regesitor";
    private String DOWN = "tb_DownLoadKey";
    // 充值金额
    private double dMoney;
    // 最小充值金额
    private double Min;
    // 订单号
    public String outer_no;
    private boolean isback = false;

    public RelativeLayout rlInput_01, rlInput_02, rlInput_03, rlInput_04;
    public TextView tvMoneyNum_01, tvMoneyNum_02, tvMoneyNum_03, tvMoneyNum_04;
    private MyHandler handler;

    private String attach;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_amount_of_charge);
        mContext = AmountOfCharge.this;
        handler = new MyHandler();
        InitView();
        Bundle bundle = getIntent().getExtras();
        type = bundle.getInt("Type");
        if (type == 4) {
            // recharge_tv_tishi.setText("温馨提示：充值免手续费，充值金额需100%消费，奖金提款不受限制" + "\n" +
            // "如未打开支付宝app,请结束支付宝进程再试一次。");
        }
    }

    private void InitView() {
        rlInput_01 = (RelativeLayout) findViewById(R.id.rl_buy_01);
        rlInput_02 = (RelativeLayout) findViewById(R.id.rl_buy_02);
        rlInput_03 = (RelativeLayout) findViewById(R.id.rl_buy_03);
        rlInput_04 = (RelativeLayout) findViewById(R.id.rl_buy_04);

        tvMoneyNum_01 = (TextView) findViewById(R.id.tv_num_buy_01);
        tvMoneyNum_02 = (TextView) findViewById(R.id.tv_num_buy_02);
        tvMoneyNum_03 = (TextView) findViewById(R.id.tv_num_buy_03);
        tvMoneyNum_04 = (TextView) findViewById(R.id.tv_num_buy_04);

        rlInput_01.setOnClickListener(this);
        rlInput_02.setOnClickListener(this);
        rlInput_03.setOnClickListener(this);
        rlInput_04.setOnClickListener(this);
        // TODO Auto-generated method stub
        btn_back = (ImageButton) findViewById(R.id.btn_back);
        btn_back.setOnClickListener(this);
        recahge_et_money = (EditText) findViewById(R.id.recahge_et_money);
        recharge_btn_ok = (Button) findViewById(R.id.recharge_btn_ok);
        // recharge_tv_tishi = (TextView) findViewById(R.id.recharge_tv_tishi);
        recharge_btn_ok.setOnClickListener(this);
        recahge_et_money.addTextChangedListener(new EditChangedListener());

        rlInput_01.setBackgroundResource(R.drawable.buy_rl_money_input_border);
        rlInput_02.setBackgroundResource(R.drawable.buy_rl_money_input_border);
        rlInput_03.setBackgroundResource(R.drawable.buy_rl_money_input_border_on);
        rlInput_04.setBackgroundResource(R.drawable.buy_rl_money_input_border);
        tvMoneyNum_01.setTextColor(getResources().getColor(R.color.main_red));
        tvMoneyNum_02.setTextColor(getResources().getColor(R.color.main_red));

        tvMoneyNum_03.setTextColor(getResources().getColor(R.color.white));
        tvMoneyNum_04.setTextColor(getResources().getColor(R.color.main_red));
        // recahge_et_money.setText("888.88");

        recahge_et_money.setSelection(recahge_et_money.getText().toString().length());
    }

    class EditChangedListener implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

            if (recahge_et_money.getText().toString().equals("50") || recahge_et_money.getText().toString().equals("100")
                    || recahge_et_money.getText().toString().equals("500")
                    || recahge_et_money.getText().toString().equals("1000")) {

            } else {

                rlInput_01.setBackgroundResource(R.drawable.buy_rl_money_input_border);
                rlInput_02.setBackgroundResource(R.drawable.buy_rl_money_input_border);
                rlInput_03.setBackgroundResource(R.drawable.buy_rl_money_input_border);
                rlInput_04.setBackgroundResource(R.drawable.buy_rl_money_input_border);
                tvMoneyNum_01.setTextColor(getResources().getColor(R.color.main_red));
                tvMoneyNum_02.setTextColor(getResources().getColor(R.color.main_red));

                tvMoneyNum_03.setTextColor(getResources().getColor(R.color.main_red));
                tvMoneyNum_04.setTextColor(getResources().getColor(R.color.main_red));
            }
        }
    }

    ;

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.rl_buy_01:
                rlInput_01.setBackgroundResource(R.drawable.buy_rl_money_input_border_on);
                rlInput_02.setBackgroundResource(R.drawable.buy_rl_money_input_border);
                rlInput_03.setBackgroundResource(R.drawable.buy_rl_money_input_border);
                rlInput_04.setBackgroundResource(R.drawable.buy_rl_money_input_border);
                tvMoneyNum_01.setTextColor(getResources().getColor(R.color.white));
                tvMoneyNum_02.setTextColor(getResources().getColor(R.color.main_red));

                tvMoneyNum_03.setTextColor(getResources().getColor(R.color.main_red));
                tvMoneyNum_04.setTextColor(getResources().getColor(R.color.main_red));
                recahge_et_money.setText("50");

                recahge_et_money.setSelection(recahge_et_money.getText().toString().length());
                break;
            case R.id.rl_buy_02:
                rlInput_01.setBackgroundResource(R.drawable.buy_rl_money_input_border);
                rlInput_02.setBackgroundResource(R.drawable.buy_rl_money_input_border_on);
                rlInput_03.setBackgroundResource(R.drawable.buy_rl_money_input_border);
                rlInput_04.setBackgroundResource(R.drawable.buy_rl_money_input_border);
                tvMoneyNum_01.setTextColor(getResources().getColor(R.color.main_red));
                tvMoneyNum_02.setTextColor(getResources().getColor(R.color.white));

                tvMoneyNum_03.setTextColor(getResources().getColor(R.color.main_red));
                tvMoneyNum_04.setTextColor(getResources().getColor(R.color.main_red));
                recahge_et_money.setText("100");

                recahge_et_money.setSelection(recahge_et_money.getText().toString().length());
                break;
            case R.id.rl_buy_03:
                rlInput_01.setBackgroundResource(R.drawable.buy_rl_money_input_border);
                rlInput_02.setBackgroundResource(R.drawable.buy_rl_money_input_border);
                rlInput_03.setBackgroundResource(R.drawable.buy_rl_money_input_border_on);
                rlInput_04.setBackgroundResource(R.drawable.buy_rl_money_input_border);
                tvMoneyNum_01.setTextColor(getResources().getColor(R.color.main_red));
                tvMoneyNum_02.setTextColor(getResources().getColor(R.color.main_red));

                tvMoneyNum_03.setTextColor(getResources().getColor(R.color.white));
                tvMoneyNum_04.setTextColor(getResources().getColor(R.color.main_red));
                recahge_et_money.setText("500");

                recahge_et_money.setSelection(recahge_et_money.getText().toString().length());
                break;
            case R.id.rl_buy_04:
                rlInput_01.setBackgroundResource(R.drawable.buy_rl_money_input_border);
                rlInput_02.setBackgroundResource(R.drawable.buy_rl_money_input_border);
                rlInput_03.setBackgroundResource(R.drawable.buy_rl_money_input_border);
                rlInput_04.setBackgroundResource(R.drawable.buy_rl_money_input_border_on);
                tvMoneyNum_01.setTextColor(getResources().getColor(R.color.main_red));
                tvMoneyNum_02.setTextColor(getResources().getColor(R.color.main_red));

                tvMoneyNum_03.setTextColor(getResources().getColor(R.color.main_red));
                tvMoneyNum_04.setTextColor(getResources().getColor(R.color.white));
                recahge_et_money.setText("1000");

                recahge_et_money.setSelection(recahge_et_money.getText().toString().length());
                break;
            case R.id.btn_back:
                AmountOfCharge.this.finish();
                break;
            case R.id.recharge_btn_ok:

                // 获取金额
                // if(ClickFilter.filter()) return;
                feePrice = recahge_et_money.getText().toString();

                if (feePrice.length() > 0 && !feePrice.equals("")) {
                    double parseInt = Double.parseDouble(feePrice);
                    if (parseInt >= 50&&parseInt <=4999) {
                        if (type == 1) {
                         getoneAliPay(feeName, feePrice, feeDesc, App.user.getUid());
                        }else if(type==2){
                            gettwoAliPay(feeName, feePrice, feeDesc, App.user.getUid());
                        }
                    } else {
                        MyToast.getToast(AmountOfCharge.this, "充值金额请在50-4999元之间!").show();
                    }
                } else {
                    Log.i(TAG, "获取金额" + recahge_et_money.getHint().toString());
                    // MyToast.getToast(AmountOfCharge.this, "请输入充值金额!").show();
                    getPay();
                }
                // if(ClickFilter.filter()) return;
                break;
            default:
                break;
        }
    }

    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            if (pd != null) {
                pd.dismiss();
            }
            switch (msg.what) {

                case 2:
                    isback = false;
//                    getSaomaXplay();
                    break;

                default:
                    break;
            }

            super.handleMessage(msg);
        }

    }


    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if (isback) {

//            pd = BaseHelper.showProgress(AmountOfCharge.this, "", "加载中...", true, false);
//            handler.sendEmptyMessageDelayed(2, 3000);

        }
    }

    private void getPay() {

        if (type == 1) {

           getoneAliPay(feeName, "888.88", feeDesc, App.user.getUid());

        }else if (type ==2)  {
            gettwoAliPay(feeName, "888.88", feeDesc, App.user.getUid());
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        finish();
    }

    /*
     * 扫码支付
     */
    private ProgressDialog pd;
    public String SaomaOuter_no;
    public String SaomaPrice;


    public void getoneAliPay(String name, String price, String desc, String uerid) {


        SaomaOuter_no = uerid;
        SaomaPrice = price;
        pd = BaseHelper.showProgress(AmountOfCharge.this, "", "加载中...", true, false);
        pd.dismiss();
        String url;

        url = "http://888.qcai888.cn/PaySH.aspx?" + "money=" + SaomaPrice + "&userID=" + SaomaOuter_no ;
        Log.e(TAG, "getoneAliPay: "+url );
        Uri uri = Uri.parse(url);
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.setData(uri);


//        if (!hasPreferredApplication(AmountOfCharge.this, intent)) {
//            intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
//        }


        startActivity(intent);
        Toast.makeText(AmountOfCharge.this, "准备跳转", Toast.LENGTH_SHORT).show();


    }
    public void gettwoAliPay(String name, String price, String desc, String uerid) {
        MySingleton mySingleton = MySingleton.getInstance(AmountOfCharge.this);
        SaomaOuter_no = uerid;
        SaomaPrice = price;
        pd = BaseHelper.showProgress(AmountOfCharge.this, "", "加载中...", true, false);
        String url;

            url = "http://m.qcai888.cn/alipay/order/create?" + "money=" + SaomaPrice + "&uid=" + SaomaOuter_no
                    + "&from=" + "0";


        StringRequest jsonObjectRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String tn) {
                pd.dismiss();
                JSONObject object= null;
                try {
                    object = new JSONObject(tn);

                    String date=object.getString("Data");

                    Log.e(TAG, "onResponse: "+ date);

                    if (date!=null){
                        {

                            Intent intent;

                                intent = Intent.parseUri("alipayqr://platformapi/startapp?saId=10000007&qrcode="
                                        + date, Intent.URI_INTENT_SCHEME);
//                                intent = Intent.parseUri( date.replaceAll("&", "%26"), Intent.URI_INTENT_SCHEME);

                                intent.addCategory(Intent.CATEGORY_BROWSABLE);
                                intent.setComponent(null);
                                startActivity(intent);

                        }
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (URISyntaxException e) {
                    isback = false;
                    e.printStackTrace();
                } catch (ActivityNotFoundException e) {
                    isback = false;
                    e.printStackTrace();
                    Toast.makeText(AmountOfCharge.this, "", Toast.LENGTH_SHORT).show();
                    // showToast("请安装支付宝客户端");
                }





            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("RealTime", "request--------success------" + error);
                pd.dismiss();
                MyToast.getToast(AmountOfCharge.this, "获取地址失败").show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                Map<String, String> params = new HashMap<String, String>();

                return params;
            }
        };

        jsonObjectRequest.setShouldCache(false);// 是否设置缓存

        mySingleton.addToRequestQueue(jsonObjectRequest);


    }

    //判断系统是否设置了默认浏览器
    public boolean hasPreferredApplication(Context context, Intent intent) {
        PackageManager pm = context.getPackageManager();
        ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return !"android".equals(info.activityInfo.packageName);
    }


}
